package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ZjNetworkEmpCommonFunction;
import com.zb.mapper.ZjNetworkEmpCommonFunctionMapper;
import com.zb.service.ZjNetworkEmpCommonFunctionService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 网点人员常用功能设置表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-03-10
 */
@Service
public class ZjNetworkEmpCommonFunctionServiceImpl extends ServiceImpl<ZjNetworkEmpCommonFunctionMapper, ZjNetworkEmpCommonFunction> implements ZjNetworkEmpCommonFunctionService {

    // 获取服务人员常用功能
    @Override
    public List<Integer> getNetworkEmpCommonFunction(AccounLoginInfo loginInfo) {
        QueryWrapper<ZjNetworkEmpCommonFunction> wrapper = new QueryWrapper<>();
        wrapper.select("type")
                .eq("network_emp_id", loginInfo.getNetworkEmpId());
        List<ZjNetworkEmpCommonFunction> commonFunctions = this.list(wrapper);
        if (CollectionUtil.isEmpty(commonFunctions)) {
            return new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        }
        return commonFunctions.stream().map(ZjNetworkEmpCommonFunction::getType).toList();
    }

    // 保存服务人员常用功能
    @Override
    public void saveNetworkEmpCommonFunction(AccounLoginInfo loginInfo, List<Integer> types) {
        Assert.notEmpty(types, "常用功能不能为空");
        Assert.isTrue(types.stream().allMatch(f -> Pattern.matches("1|2|3|4|5|6|7|8|9", f.toString())), "常用功能类型参数不合法");
        deleteByNetworkEmpId(loginInfo.getNetworkEmpId());
        List<ZjNetworkEmpCommonFunction> commonFunctions = new ArrayList<>();
        ZjNetworkEmpCommonFunction commonFunction = null;
        for (Integer type : types) {
            commonFunction = new ZjNetworkEmpCommonFunction();
            commonFunction.setId(IdWorker.getId());
            commonFunction.setNetworkEmpId(loginInfo.getNetworkEmpId());
            commonFunction.setType(type);
            commonFunctions.add(commonFunction);
        }
        this.saveBatch(commonFunctions);
    }

    // 根据人员ID删除常用功能
    @Override
    public void deleteByNetworkEmpId(Long networkEmpID) {
        QueryWrapper<ZjNetworkEmpCommonFunction> wrapper = new QueryWrapper<>();
        wrapper.eq("network_emp_id", networkEmpID);
        this.remove(wrapper);
    }


}
